const {isPlainObject} = require('./common');

module.exports = function autoScroll(page, callback, args = null) {
    return page.evaluate(() => {
        return new Promise((resolve) => {
            const options = {
                distance: 150,
                timeout: 500,
                maxPageHeight: 0,
                counter: 100
            };

            if (isPlainObject(args)) {
                Object.assign(options, args);
            }

            let totalHeight = 0;
            let counter = 0;
            const distance = options.distance || 150;
            const timer = setInterval(async () => {
                counter++;
                const scrollHeight = document.body.scrollHeight;
                window.scrollBy(0, distance);

                if (typeof callback === 'function') {
                    await callback();
                }

                totalHeight += distance;
                let stop = totalHeight >= scrollHeight;

                if (options.maxPageHeight) {
                    stop = stop || totalHeight >= options.maxPageHeight;
                }

                if (options.counter) {
                    stop = stop || counter >= options.counter;
                }

                if (stop) {
                    clearInterval(timer);
                    resolve();
                }
            }, options.timeout || 500);
        })
    });
}